package com.app.coderead;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

@SuppressWarnings("serial")
public class UploadCodeServlet extends HttpServlet {
    private final String CRLF = "\r\n";
    private final Logger log;
    private final String TAG;
    private CodeReadBean bean;

    {
        TAG = this.getClass().getName();
        log = Logger.getLogger(TAG);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    }

    public void processRequest(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator uploadItemIterator = upload.getItemIterator(req);
            bean = new CodeReadBean();
            Map<String, String> map = bean.getMap();

            while (uploadItemIterator.hasNext()) {
                FileItemStream uploadDataItem = uploadItemIterator.next();
                if (uploadDataItem.isFormField()) {// form field
                    // set field info to bean
                    map.put(uploadDataItem.getFieldName(),
                            Streams.asString(uploadDataItem.openStream()));

                } else {// data stream

                    InputStream uploadDataStream = uploadDataItem.openStream();

                    // 串流依據 encoding 編碼 並使用buffer
                    BufferedReader uploadDataReader = new BufferedReader(new InputStreamReader(
                            uploadDataStream, "UTF-8"));
                    uploadDataReader = new BufferedReader(uploadDataReader);
                    try {
                        String line = null;
                        StringBuffer sb = new StringBuffer();
                        int lines = 0;
                        while (null != (line = uploadDataReader.readLine())) {
                            lines++;
                            sb.append(line).append(CRLF);
                        }
                        log.info("lines : " + lines);
                        // set to request scope
                        bean.setLines(lines);
                        req.setAttribute("bean", bean);
                        req.setAttribute("doc", sb);
                    } finally {
                        if (uploadDataReader != null) {
                            uploadDataReader.close();
                        }
                    }
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        RequestDispatcher view = req.getRequestDispatcher("/page/transfer.jsp");
        view.forward(req, resp);
    }
}
